#!/bin/bash

# 服务监控脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
CONTAINER_NAME="git-env-dev"
LOG_FILE="logs/service-monitor.log"

echo -e "${BLUE}启动服务监控...${NC}"

# 创建日志目录
mkdir -p logs

# 监控函数
monitor_service() {
    local service_name=$1
    local check_command=$2
    local restart_command=$3

    echo -e "${BLUE}监控服务: ${service_name}${NC}" | tee -a $LOG_FILE

    while true; do
        if ! eval "$check_command"; then
            echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ${service_name} 服务异常，尝试重启${NC}" | tee -a $LOG_FILE

            if eval "$restart_command"; then
                echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] ${service_name} 重启成功${NC}" | tee -a $LOG_FILE
            else
                echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ${service_name} 重启失败${NC}" | tee -a $LOG_FILE
            fi
        fi

        sleep 30
    done
}

# 检查PostgreSQL
check_postgresql() {
    docker exec "${CONTAINER_NAME}" pg_isready -h localhost -p 5432 -U postgres &>/dev/null
}

# 重启PostgreSQL
restart_postgresql() {
    docker exec "${CONTAINER_NAME}" service postgresql restart
}

# 检查Redis
check_redis() {
    docker exec "${CONTAINER_NAME}" redis-cli -h localhost -p 6379 ping | grep -q "PONG"
}

# 重启Redis
restart_redis() {
    docker exec "${CONTAINER_NAME}" service redis-server restart
}

# 检查FastAPI
check_fastapi() {
    curl -s -f "http://localhost:7001/health" &>/dev/null || curl -s -f "http://localhost:7001/docs" &>/dev/null
}

# 重启FastAPI
restart_fastapi() {
    docker exec "${CONTAINER_NAME}" bash -c "
        if [ -f /app/logs/app/fastapi.pid ]; then
            kill \$(cat /app/logs/app/fastapi.pid) || true
            rm -f /app/logs/app/fastapi.pid
        fi
        cd /app/backend
        nohup uvicorn app.main:app --host 0.0.0.0 --port 7001 --reload > /app/logs/app/fastapi.log 2>&1 &
        echo \$! > /app/logs/app/fastapi.pid
    "
}

# 检查Celery Worker
check_celery_worker() {
    docker exec "${CONTAINER_NAME}" pgrep -f "celery.*worker" &>/dev/null
}

# 重启Celery Worker
restart_celery_worker() {
    docker exec "${CONTAINER_NAME}" bash -c "
        if [ -f /app/logs/celery/celery-worker.pid ]; then
            kill \$(cat /app/logs/celery/celery-worker.pid) || true
            rm -f /app/logs/celery/celery-worker.pid
        fi
        cd /app/backend
        nohup celery -A app.celery worker --loglevel=info --concurrency=2 > /app/logs/celery/celery-worker.log 2>&1 &
        echo \$! > /app/logs/celery/celery-worker.pid
    "
}

# 检查Celery Beat
check_celery_beat() {
    docker exec "${CONTAINER_NAME}" pgrep -f "celery.*beat" &>/dev/null
}

# 重启Celery Beat
restart_celery_beat() {
    docker exec "${CONTAINER_NAME}" bash -c "
        if [ -f /app/logs/celery/celery-beat.pid ]; then
            kill \$(cat /app/logs/celery/celery-beat.pid) || true
            rm -f /app/logs/celery/celery-beat.pid
        fi
        cd /app/backend
        nohup celery -A app.celery beat --loglevel=info --schedule=/app/logs/celery/celerybeat-schedule > /app/logs/celery/celery-beat.log 2>&1 &
        echo \$! > /app/logs/celery/celery-beat.pid
    "
}

# 检查Vue.js
check_vuejs() {
    curl -s -f "http://localhost:8080" &>/dev/null
}

# 重启Vue.js
restart_vuejs() {
    docker exec "${CONTAINER_NAME}" bash -c "
        if [ -f /app/logs/app/vuejs.pid ]; then
            kill \$(cat /app/logs/app/vuejs.pid) || true
            rm -f /app/logs/app/vuejs.pid
        fi
        cd /app/frontend
        nohup npm run dev > /app/logs/app/vuejs.log 2>&1 &
        echo \$! > /app/logs/app/vuejs.pid
    "
}

# 启动监控进程
echo -e "${GREEN}启动后台监控进程...${NC}"

# 在后台启动各个服务的监控
monitor_service "PostgreSQL" "check_postgresql" "restart_postgresql" &
MONITOR_PID1=$!

monitor_service "Redis" "check_redis" "restart_redis" &
MONITOR_PID2=$!

monitor_service "FastAPI" "check_fastapi" "restart_fastapi" &
MONITOR_PID3=$!

monitor_service "Celery Worker" "check_celery_worker" "restart_celery_worker" &
MONITOR_PID4=$!

monitor_service "Celery Beat" "check_celery_beat" "restart_celery_beat" &
MONITOR_PID5=$!

monitor_service "Vue.js" "check_vuejs" "restart_vuejs" &
MONITOR_PID6=$!

# 保存监控进程ID
echo $MONITOR_PID1 > logs/monitor-postgresql.pid
echo $MONITOR_PID2 > logs/monitor-redis.pid
echo $MONITOR_PID3 > logs/monitor-fastapi.pid
echo $MONITOR_PID4 > logs/monitor-celery-worker.pid
echo $MONITOR_PID5 > logs/monitor-celery-beat.pid
echo $MONITOR_PID6 > logs/monitor-vuejs.pid

echo -e "${GREEN}服务监控已启动${NC}"
echo -e "${YELLOW}使用 'kill \$(cat logs/monitor-*.pid)' 停止所有监控进程${NC}"
echo -e "${YELLOW}查看监控日志: tail -f $LOG_FILE${NC}"

# 等待所有监控进程
wait